package com.ht.oss.controller;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import com.ht.oss.config.BucketsConfig;
import com.ht.oss.dto.Res;
import com.ht.oss.service.OssService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

@RestController
@Tag(name = "oss 控制器")
public class OssController {

    @Autowired
    private BucketsConfig bucketsConfig;

    @Autowired
    private OssService ossService;

    // @PostMapping("/img")
    // public Res<String> upLoadImage(@RequestParam("file") MultipartFile file) {
    //     try (
    //             InputStream in = file.getInputStream();
    //             ByteArrayOutputStream bos = new ByteArrayOutputStream();
    //     ) {
    //         IoUtil.copy(in, bos);
    //         byte[] byteArray = bos.toByteArray();
    //         String type = FileTypeUtil.getType(new ByteArrayInputStream(byteArray));
    //         if (TypeCheckUtil.isImage(type)) {
    //             String md5 = ossService.upload(bos.toByteArray(), bucketsConfig.getImageBucket(), type);
    //             return Res.ok(null, md5);
    //         } else {
    //             return Res.fail("文件异常，请重新选择文件");
    //         }
    //     } catch (IOException e) {
    //         throw new IORuntimeException(e);
    //     }
    // }
    //
    // @GetMapping("/img/{md5}")
    // public void downloadImage(@PathVariable("md5") String md5, HttpServletResponse response) {
    //     File file = ossService.download(bucketsConfig.getImageBucket(), md5);
    //     try (
    //             InputStream is = file == null ? null : Files.newInputStream(file.toPath());
    //             ServletOutputStream os = response.getOutputStream();
    //     ) {
    //         if (is == null) {
    //             response.setContentType(ContentType.JSON.getValue());
    //             os.write(JSONUtil.toJsonStr(Res.<Void>fail("图片不存在，请稍后再试")).getBytes(StandardCharsets.UTF_8));
    //             return;
    //         }
    //         response.setContentType("image/" + FileUtil.getSuffix(file));
    //         IoUtil.copy(is, os);
    //     } catch (IOException e) {
    //         throw new RuntimeException(e);
    //     }
    // }
    //
    // @DeleteMapping("/img/{md5}")
    // public Res<String> removeImage(@PathVariable("md5") String md5) {
    //     if (ossService.deleteFile(bucketsConfig.getImageBucket(), md5)) {
    //         return Res.ok();
    //     } else {
    //         return Res.fail("删除失败，请重试");
    //     }
    // }

    @PostMapping
    @Operation(summary = "上传对象")
    public Res<String> upLoad(@RequestParam("file") MultipartFile file) {
        try (
                InputStream in = file.getInputStream();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ) {
            IoUtil.copy(in, bos);
            byte[] byteArray = bos.toByteArray();
            String md5 = ossService.upload(byteArray);
            return Res.ok(null, md5);
        } catch (IOException e) {
            throw new IORuntimeException(e);
        }
    }

    @GetMapping("/{md5}")
    @Operation(summary = "下载对象")
    public void download(@PathVariable("md5") String md5, HttpServletResponse response) {
        File file = ossService.download(bucketsConfig.getObjBucket(), md5);
        try (
                InputStream is = file == null ? null : Files.newInputStream(file.toPath());
                ServletOutputStream os = response.getOutputStream();
        ) {
            if (is == null) {
                response.setContentType(ContentType.JSON.getValue());
                os.write(JSONUtil.toJsonStr(Res.<Void>fail("文件不存在，请稍后再试")).getBytes(StandardCharsets.UTF_8));
                return;
            }
            IoUtil.copy(is, os);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @DeleteMapping("/{md5}")
    @Operation(summary = "删除对象")
    public Res<String> remove(@PathVariable("md5") String md5) {
        if (ossService.deleteFile(bucketsConfig.getObjBucket(), md5)) {
            return Res.ok();
        } else {
            return Res.fail("删除失败，请重试");
        }
    }
}
